package demo6;

import java.util.LinkedList;
import java.util.Queue;

class MyStack {
    Queue<Integer> queue1;
    Queue<Integer> queue2;

    public MyStack() {
        this.queue1 = new LinkedList<>();
        this.queue2 = new LinkedList<>();
    }

    public void push(int x) {
        if (empty()) {
            queue1.offer(x);
            return;
        }
        if (queue1.isEmpty()) {
            queue2.offer(x);
        } else {
            queue1.offer(x);
        }
    }


    public int pop() {
        if (empty()) {
            return -1;
        }

        if (!queue1.isEmpty()) {
            int size = queue1.size() - 1;
            for (int i = 0; i < size; i++) {
                queue2.offer(queue1.poll());
            }
            return queue1.poll();
        } else {
            int size = queue2.size() - 1;
            for (int i = 0; i < size; i++) {
                queue1.offer(queue2.poll());
            }
            return queue2.poll();
        }

    }

    public int top() {
        if (empty()) {
            return -1;
        }
        if (!queue1.isEmpty()) {
            int size = queue1.size();
            int val = 0;
            for (int i = 0; i < size; i++) {
                val = queue1.poll();
                queue2.offer(val);
            }
            return val;
        } else {
            int size = queue2.size();
            int val = 0;
            for (int i = 0; i < size; i++) {
                val = queue2.poll();
                queue1.offer(val);
            }
            return val;
        }
    }

    public boolean empty() {
        return queue2.isEmpty() && queue1.isEmpty();
    }

}